<template>
  <div>
    <!-- <slot></slot><span :id="eleId" :class="countClass"></span> -->
    <slot name="left"></slot><span ref="countTo" :id="eleId" :class="countClass"></span><slot name="right"></slot>
  </div>
</template>
<script>
import CountUp from 'countup'
export default {
  name: 'CountTo',
  computed: {
    eleId () {
      return `count_up_${this._uid}`
    },
    countClass () {
      return [
        'count-to-number',
        this.countClassName
      ]
    }
  },
  data () {
    return {
      counter: {}
    }
  },
  props: {
    /**
     * @description 起始值
     */
    startVal: {
      type: Number,
      default: 0
    },
    /**
     * @description 最终值
     */
    endVal: {
      type: Number,
      required: true // 必传值
    },
    /**
     * @description 动画延迟执行时间（毫秒）
     */
    delay: {
      type: Number,
      default: 0
    },
    /**
     * @description 小数点后保留几位小数
     */
    decimals: {
      type: Number,
      default: 0
    },
    /**
     * @description 渐变时长
     */
    duration: {
      type: Number,
      default: 2
    },
    /**
     * @description 是否使用变速
     */
    useEasing: {
      type: Boolean,
      default: false
    },
    /**
     * @description 是否使用分组 4,300
     */
    useGrouping: {
      type: Boolean,
      default: true
    },
    /**
     * @description 分组符号
     */
    separator: {
      type: String,
      default: ','
    },
    /**
     * @description 整数与小数的分隔符号
     */
    decimal: {
      type: String,
      default: '.'
    },
    /**
     * @description 类名
     */
    countClassName: {
      type: String,
      default: ''
    }
  },
  watch: {
    endVal (newVal, oldVal) {
      this.counter.update(newVal)
      setTimeout(() => {
        this.$emit('on-animation-end', Number(this.getCountTo()))
      }, this.duration * 1000 + 5)
    }
  },
  mounted () {
    this.$nextTick(() => {
      // const options = {
      //   useEasing: true,
      //   useGrouping: true,
      //   separator: ',',
      //   decimal: '.'
      // };
      this.counter = new CountUp(this.eleId, this.startVal, this.endVal, this.decimals, this.duration, {
        useEasing: this.useEasing,
        useGrouping: this.useGrouping,
        separator: this.separator,
        decimal: this.decimal
      })
      // if (!counter.error) {
      //   counter.start();
      // } else {
      //   console.error(counter.error);
      // }
      setTimeout(() => {
        this.counter.start()
      }, this.delay)
    })
  },
  methods: {
    getCountTo () {
      // console.log(this.$refs.countTo.innerText)
      return this.$refs.countTo.innerText
    }
  }
}
</script>
<style lang="less" scoped>
  @import './count-to.less';
</style>
